package com.hibox.controller;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hibox.common.annotation.Anonymous;
import com.hibox.common.core.domain.AjaxResult;
import com.hibox.common.core.redis.RedisCache;
import com.hibox.common.core.text.Convert;
import com.hibox.common.utils.DateUtils;
import com.hibox.common.utils.uuid.IdUtils;
import com.hibox.constant.MemberConstant;
import com.hibox.domain.Address;
import com.hibox.domain.Goods;
import com.hibox.domain.Member;
import com.hibox.domain.Order;
import com.hibox.service.AddressService;
import com.hibox.service.GoodsService;
import com.hibox.service.MemberService;
import com.hibox.service.OrderService;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import com.hibox.util.payment.AlipayUtil;
import com.hibox.vo.OrderPageParams;
import org.apache.commons.math3.analysis.function.Add;
import org.springframework.web.bind.annotation.*;

/**
 * 订单表(Order)表控制层
 *
 * @author WangFK
 * @since 2023-08-17 16:30:23
 */
@RestController
@RequestMapping("/store/order")
public class OrderController {
    /**
     * 服务对象
     */
    @Resource
    private OrderService orderService;
    @Resource
    private GoodsService goodsService;
    @Resource
    private AddressService addressService;
    @Resource
    private MemberService memberService;
    @Resource
    private RedisCache redisCache;
    @Resource
    private AlipayUtil alipayUtil;

    @Anonymous
    @GetMapping("/success")
    public AjaxResult success() {
        return AjaxResult.success();
    }

    @Anonymous
    @GetMapping("/pay")
    public void pay(String memberId, String goodsId, String addressId) throws AlipayApiException, IOException {
        String key = MemberConstant.MEMBER_INFO + memberId;
        Member value = redisCache.getCacheObject(key);
        if (ObjectUtil.isEmpty(value)) {
            value = memberService.getById(memberId);
            redisCache.setCacheObject(key, value, 1, TimeUnit.HOURS);
        }
        Goods byId = goodsService.getById(goodsId);
        Order order = new Order();
        String orderId = "Hi-Box_" + IdUtils.fastSimpleUUID();
        order.setOrderId(orderId);
        // 地址信息
        Address one = addressService.getById(addressId);
//        if (byId==null){
//            return AjaxResult.error("商品下架");
//        }
        order.setMemberId(Convert.toLong(value.getId()));
        order.setGoodsId(byId.getId());
        order.setAddressId(one.getId());
        order.setPayStatus("0");
        order.setPhone(one.getPhone());
        order.setAddress(one.getProvinceName() + "|"
                + one.getCityName() + "|"
                + one.getDistrictName() + "|"
                + one.getDetail());
        order.setMemberName(value.getMemberName());
        order.setConsignee(one.getConsignee());
        order.setAmount(byId.getSellingPrice());
        orderService.save(order);
        alipayUtil.pay(orderId, byId.getSellingPrice().toString(), "Hi-Box_" + byId.getName());
    }


    @Anonymous
    @PostMapping("/notify")
    public void notifyUrl() throws IOException {
        Map map = alipayUtil.payNotify();
        LambdaUpdateWrapper<Order> lqw = new LambdaUpdateWrapper<Order>()
                .eq(Order::getOrderId, map.get("out_trade_no"));
        Order one = orderService.getOne(lqw);
        Order order = new Order();
        order.setId(one.getId());
        order.setCheckoutTime(DateUtils.getNowDate());
        order.setPayStatus("1");
        orderService.updateById(order);
    }

    /**
     * 分页
     *
     * @param params
     * @return
     */
    @GetMapping("/list")
    public AjaxResult list(OrderPageParams params) {
        Page<Order> orderPage = new Page<>(params.getPageNum(), params.getPageSize());
        LambdaUpdateWrapper<Order> lqw = new LambdaUpdateWrapper<Order>()
                .eq(ObjectUtil.isNotEmpty(params.getPayMethod()), Order::getPayMethod, params.getPayMethod())
                .eq(ObjectUtil.isNotEmpty(params.getPayStatus()), Order::getPayStatus, params.getPayStatus())
                .eq(ObjectUtil.isNotEmpty(params.getGoodsId()), Order::getGoodsId, params.getGoodsId())
                .like(ObjectUtil.isNotEmpty(params.getOrderTime()), Order::getOrderTime, params.getOrderTime());
        String search = params.getSearch();
        if (ObjectUtil.isNotEmpty(search)) {
            lqw.like(Order::getPhone, search).or()
                    .like(Order::getAddress, search).or()
                    .like(Order::getMemberName, search).or()
                    .like(Order::getConsignee, search);
        }
        orderPage = orderService.page(orderPage, lqw);
        List<Order> records = orderPage.getRecords();
        if (records.isEmpty()) {
            return AjaxResult.success();
        }
        records.stream().forEach(item -> {
            Goods byId = goodsService.getById(item.getGoodsId());
            item.setGoodsName(byId.getName());
            item.setGoodsImage(byId.getImg());
        });
        return AjaxResult.success()
                .put("rows", records)
                .put("total", orderPage.getTotal());
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public AjaxResult selectOne(@PathVariable Serializable id) {
        Order byId = orderService.getById(id);
        return AjaxResult.success(byId);
    }

    /**
     * 新增数据
     *
     * @param order 实体对象
     * @return 新增结果
     */
    @PostMapping
    public AjaxResult insert(@RequestBody Order order) {
        String orderId = IdUtils.fastSimpleUUID();
        if (ObjectUtil.isEmpty(order.getAddressId())) {
            return AjaxResult.error("地址为空");
        }
        if (ObjectUtil.isEmpty(order.getGoodsId())) {
            return AjaxResult.error("商品为空");
        }
        if (ObjectUtil.isEmpty(order.getMemberId())) {
            return AjaxResult.error("会员为空");
        }
        if (ObjectUtil.isNotEmpty(order.getId())) {
            return update(order);
        }
        order.setOrderId(orderId);
        updateAddress(order);
        Member byId1 = memberService.getById(order.getMemberId());
        if (byId1 != null) {
            order.setMemberName(byId1.getNickName());
        }
        return orderService.save(order) ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 更新手机号和地址
     *
     * @param order
     */
    private void updateAddress(Order order) {
        Address byId = addressService.getById(order.getAddressId());
        if (byId != null) {
            order.setPhone(byId.getPhone());
            String addressName = byId.getProvinceName() + "|"
                    + byId.getCityName() + "|"
                    + byId.getDistrictName() + "|"
                    + byId.getDetail();
            order.setAddress(addressName);
            order.setConsignee(byId.getConsignee());
        }
    }

    /**
     * 修改数据
     *
     * @param order 实体对象
     * @return 修改结果
     */
    @PutMapping
    public AjaxResult update(@RequestBody Order order) {
        // 修改地址信息
        Order byId = orderService.getById(order.getId());
        if (!byId.getAddressId().equals(order.getAddressId())) {
            updateAddress(order);
        }
        return orderService.updateById(order) ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 删除数据
     *
     * @param id 主键结合
     * @return 删除结果
     */
    @DeleteMapping("{id}")
    public AjaxResult delete(@PathVariable String id) {
        List<String> split = StrUtil.split(id, ",");
        return orderService.removeBatchByIds(split) ? AjaxResult.success() : AjaxResult.error();
    }
}

